<?php
/**
 * 管理员管理知识点
 */

class Admin_knowledge_point extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        //登陆状态检测
        if (!$this->session->userdata('r_user_in')) {
            redirect('home');
        }
        //权限检测
        if ($this->session->userdata('r_role_id') != 1) {
            redirect('home');
        }
    }

    /**
     * 知识点管理的主页面
     * @return [type] [description]
     */
    public function index()
    {
        $data['title']='知识点管理';
        $this->load->model('knowledge_point_model');
        $data['knowledge_points']=$this->knowledge_point_model->get_all_with_test_point();

        $this->load->model('test_point_model');
        $data['test_points']=$this->test_point_model->get_all();

        $this->load->view('admin_knowledge_point/index', $data);
    }

    /**
     * 添加知识点,包括解释的添加
     * post
     */
    public function add($test_point_id)
    {
        if ($this->form_validation->run('admin_knowledge_point/add')) {
            $content=$this->input->post('content');
            $time_stamp=$this->input->post('time_stamp');
            $explanation=$this->input->post('explanation');

            $test_point_id=$this->input->post('test_point_id');

            //加载模型
            $this->load->model('test_point_model');
            $test_point=$this->test_point_model->get_by_id($test_point_id);
            if (!$test_point) {
                return $this->load->view('error');
            }

            $item = array(
                'content' => $content,
                'test_point_id' => $test_point_id,
                'explanation' => $explanation
                 );

            $this->load->model('knowledge_point_model');
            $this->knowledge_point_model->add($item);
            $knowledge_point_id=$this->db->insert_id();
            //配置上传图片到upload目的信息
            if (is_dir('./uploads/exp/'.$time_stamp)) {
                if (!is_dir('./uploads/exp/'.$knowledge_point_id)) {
                    mkdir('./uploads/exp/'.$knowledge_point_id);
                }
                //处理图片
                if (file_exists('./uploads/exp/'.$time_stamp.'/pic.jpg')) {
                    //拷贝
                    copy('./uploads/exp/'.$time_stamp.'/pic.jpg', './uploads/exp/'.$knowledge_point_id.'/pic.jpg');
                    copy('./uploads/exp/'.$time_stamp.'/pic_thumb.jpg', './uploads/exp/'.$knowledge_point_id.'/pic_thumb.jpg');

                    //删除
                    unlink('./uploads/exp/'.$time_stamp.'/pic.jpg');
                    unlink('./uploads/exp/'.$time_stamp.'/pic_thumb.jpg');

                    //写入数据库
                    $path='./uploads/exp/'.$knowledge_point_id.'/';
                    
                    $item= array(
                        'picture' => $path,
                         );
                    $this->knowledge_point_model->update($knowledge_point_id, $item);
                }
            }

            rmdir('./uploads/exp/'.$time_stamp);

            $this->session->set_flashdata('message', '操作成功');
            redirect('admin_test_point/check/'.$test_point_id);
        }

        //导航到知识点管理页面
        $data['title']='添加知识点';
        $this->load->model('test_point_model');
        if (!$this->test_point_model->get_by_id($test_point_id)) {
            return $this->load->view('error');
        }
        $data['test_point_id']=$test_point_id;
        $data['time_stamp']=time();

        $this->load->view('admin_knowledge_point/add', $data);
    }

    /**
     * 删除一个知识点
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delete($id)
    {
        //加载模型
        $this->load->model('knowledge_point_model');
        $knowledge_point_id=$id;
        $knowledge_point=$this->knowledge_point_model->get_by_id($id);
        if (!$knowledge_point) {
            return $this->load->view('error');
        }

        $question_in_knowledge_point = $this->knowledge_point_model->get_question_by_knowledge_point_id($knowledge_point_id);
        if (!$question_in_knowledge_point) {
            if ($this->knowledge_point_model->delete($knowledge_point_id)) {
                //处理图片
                $this->delete_files_by_dir('./uploads/exp/'.$knowledge_point_id);
                rmdir('./uploads/exp/'.$knowledge_point_id);
                $this->session->set_flashdata('message', '操作成功');
            } else {
                $this->session->set_flashdata('message', '操作失败');
            }
        } else {
            $this->session->set_flashdata('message', '操作失败（存在引用此知识点的问题）');
        }
        redirect('admin_test_point/check/'.$knowledge_point['test_point_id']);
    }

    /**
     * 编辑一个知识点
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function edit($id=0, $from_question_id=0)
    {
        if ($id==0) {
            //post方法
            $knowledge_point_id=$this->input->post('knowledge_point_id');
            $this->load->model('knowledge_point_model');
            $knowledge_point=$this->knowledge_point_model->get_by_id($knowledge_point_id);
            if (!$knowledge_point) {
                return $this->load->view('error');
            }

            if ($this->form_validation->run('admin_knowledge_point/edit')) {
                $content=$this->input->post('content');
                $time_stamp=$this->input->post('time_stamp');
                $explanation=$this->input->post('explanation');

                $test_point_id=$this->input->post('test_point_id');
                $from_question_id=$this->input->post('from_question_id');
                $item = array(
                    'content' => $content,
                    'explanation' => $explanation);

                
                if ($this->knowledge_point_model->update($knowledge_point_id, $item)) {
                    //配置上传图片到upload目的信息
                    if (is_dir('./uploads/exp/'.$time_stamp)) {
                        if (!is_dir('./uploads/exp/'.$knowledge_point_id)) {
                            mkdir('./uploads/exp/'.$knowledge_point_id);
                        }
                        //处理图片
                        if (file_exists('./uploads/exp/'.$time_stamp.'/pic.jpg')) {
                            //拷贝
                            copy('./uploads/exp/'.$time_stamp.'/pic.jpg', './uploads/exp/'.$knowledge_point_id.'/pic.jpg');
                            copy('./uploads/exp/'.$time_stamp.'/pic_thumb.jpg', './uploads/exp/'.$knowledge_point_id.'/pic_thumb.jpg');

                            //删除
                            unlink('./uploads/exp/'.$time_stamp.'/pic.jpg');
                            unlink('./uploads/exp/'.$time_stamp.'/pic_thumb.jpg');

                            //写入数据库
                            $path='./uploads/exp/'.$knowledge_point_id.'/';
                            
                            $item= array(
                                'picture' => $path,
                                 );
                            $this->knowledge_point_model->update($knowledge_point_id, $item);
                        }
                    }

                    rmdir('./uploads/exp/'.$time_stamp);

                    $this->session->set_flashdata('message', '操作成功');
                    if ($from_question_id==0) {
                        redirect('admin_test_point/check/'.$test_point_id);
                    } else {
                        redirect('admin_question/check/'.$from_question_id);
                    }
                } else {
                    $this->session->set_flashdata('message', '操作失败');
                }
            }
        }
        
        //如果还没有获得id参数，post的id传入失败
        if ($id==0) {
            $this->load->view('error');
        }
        
        //get方法
        $this->load->model('knowledge_point_model');
        $knowledge_point=$this->knowledge_point_model->get_by_id($id);
        if (!$knowledge_point) {
            return $this->load->view('error');
        }
        $data['knowledge_point']=$knowledge_point;
        $time_stamp=time();
        $data['time_stamp']=$time_stamp;
        //将上传的文件，复制到临时的时间戳文件夹中
        if (!is_dir('./uploads/exp/'.$time_stamp)) {
            mkdir('./uploads/exp/'.$time_stamp);
        }
        
        $picture_exist=false;
        //处理选项的图片
        if (file_exists('./uploads/exp/'.$knowledge_point['id'].'/pic.jpg')) {
            //拷贝
            copy('./uploads/exp/'.$knowledge_point['id'].'/pic.jpg', './uploads/exp/'.$time_stamp.'/pic.jpg');
            copy('./uploads/exp/'.$knowledge_point['id'].'/pic_thumb.jpg', './uploads/exp/'.$time_stamp.'/pic_thumb.jpg');
            $picture_exist=true;
        }

        $data['picture_exist']=$picture_exist;
        //如果是从check题目过来的请求，则设置question_id
        $data['from_question_id']=$from_question_id;
        $data['title']='编辑知识点';
        $this->load->view('admin_knowledge_point/edit', $data);
    }



    //处理ajax上传文件
    public function ajax_file_upload($time_stamp, $name)
    {
        $config['upload_path'] = './uploads/exp/'.$time_stamp;
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '100000';
        $config['max_width']  = '2048';
        $config['max_height']  = '1536';
        $this->load->library('upload', $config);

        //上传图片
        $config['file_name']=$name.'.jpg';
        $this->upload->initialize($config);
        if (!is_dir('./uploads/exp/'.$time_stamp)) {
            mkdir('./uploads/exp/'.$time_stamp);
        }
        if (file_exists('./uploads/exp/'.$time_stamp.'/'.$name.'.jpg')) {
            unlink('./uploads/exp/'.$time_stamp.'/'.$name.'.jpg');
            unlink('./uploads/exp/'.$time_stamp.'/'.$name.'_thumb.jpg');
        }
        $data=array('state' => 'success' );
        //初始化图片的数据模型
        if ($this->upload->do_upload('pic_input')) {
            $config['image_library'] = 'gd2';

            $config['source_image'] = './uploads/exp/'.$time_stamp.'/'.$name.'.jpg';
            $config['create_thumb'] = true;
            $config['maintain_ratio'] = true;
            $config['width'] = 90;
            $config['height'] = 90;

            $this->load->library('image_lib', $config);

            $this->image_lib->resize();
        }
    }

    //删除已经上传的图片
    public function ajax_delete_pic($time_stamp)
    {
        if (file_exists('./uploads/exp/'.$time_stamp.'/pic.jpg')) {
            unlink('./uploads/exp/'.$time_stamp.'/pic.jpg');
            unlink('./uploads/exp/'.$time_stamp.'/pic_thumb.jpg');
        }
    }

    //根据目录删除目录下的所有文件
    public function delete_files_by_dir($dir)
    {
        //删除目录下的文件：
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if ($file!="." && $file!="..") {
                $fullpath=$dir."/".$file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    deldir($fullpath);
                }
            }
        }
    }

    /**
     * 在离开页面的时候删除临时图片数据
     * @param  [type] $time_stamp [description]
     * @return [type]             [description]
     */
    public function delete_temp_picture($time_stamp)
    {
        //删除临时文件夹中的图片
        $this->delete_files_by_dir('./uploads/exp/'.$time_stamp);
        //删除临时文件夹
        rmdir('./uploads/exp/'.$time_stamp);
    }
}
